package com.eascs.archive.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.eascs.admin.common.vo.ModelResult;
import com.eascs.app.dao.PageResult;
import com.eascs.app.dao.SqlPageQuery;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.archive.dao.ArchiveRecordDao;
import com.eascs.archive.entity.ArchiveRecordEntity;
import com.eascs.archive.entity.CreditArchiveRecordEntity;
import com.eascs.archive.form.ArchivequeryForm;
import com.eascs.archive.service.ArchiveRecordService;
import com.eascs.common.util.StringUtil;
import com.eascs.web.sso.UserHolder;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ArchiveRecordServiceImpl implements ArchiveRecordService {
	protected final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private ArchiveRecordDao archiveRecordDao;

	@Override
	public ModelResult<Boolean> insertArchiveRecord(ArchiveRecordEntity entity) {
		ModelResult<Boolean> modelResult = new ModelResult<Boolean>();
		if (entity == null) {
			return modelResult;
		}
		try {
			Date now = new Date();
			entity.setCreateTime(now);
			entity.setUpdateTime(now);
			archiveRecordDao.insertArchiveRecord(entity);
			modelResult.setModel(true);
			return modelResult;
		} catch (Exception e) {
			logger.error("新增归档失败 errorMsg:[{}],entity:[{}]", e, entity.toString());
			modelResult.withError("ArchiveRecordServiceImpl.insertArchiveRecord", "新增归档失败:" + e.getMessage());
			return modelResult;
		}
	}

	@Override
	public ModelResult<Boolean> updateArchiveRecord(ArchiveRecordEntity entity) {
		ModelResult<Boolean> modelResult = new ModelResult<Boolean>();
		if (entity == null) {
			return modelResult;
		}
		try {
			StringBuffer sb = new StringBuffer();
			List<Object> param = new ArrayList<>();
			sb.append("UPDATE o2o_archive_record SET content_json=?,updator=?,update_time=?");
			param.add(entity.getContentJson());
			param.add(entity.getUpdator());
			param.add(new Date());
			if (StringUtils.isNotBlank(entity.getArchiveNo())) {
				sb.append(",archive_no=?");
				param.add(entity.getArchiveNo());
			}
			if (StringUtils.isNotBlank(entity.getSendTime())) {
				sb.append(",send_time=?");
				param.add(entity.getSendTime());
			}
			if (StringUtils.isNotBlank(entity.getSendCompany())) {
				sb.append(",send_company=?");
				param.add(entity.getSendCompany());
			}
			if (StringUtils.isNotBlank(entity.getSendNo())) {
				sb.append(",send_no=?");
				param.add(entity.getSendNo());
			}
			sb.append(" WHERE loanapply_no=? AND bank_type_id=? AND form_type_id=?");
			param.add(entity.getLoanapplyNo());
			param.add(entity.getBankTypeId());
			param.add(entity.getFormTypeId());
			archiveRecordDao.execute(sb.toString(), param.toArray());
			modelResult.setModel(true);
			return modelResult;
		} catch (Exception e) {
			logger.error("修改归档失败 errorMsg:[{}],entity:[{}]", e, entity.toString());
			modelResult.withError("ArchiveRecordServiceImpl.updateArchiveRecord", "修改归档失败:" + e.getMessage());
			return modelResult;
		}
	}

	@Override
	public ModelResult<ArchiveRecordEntity> queryArchiveRecord(String loanapplyNo, String bankType, String formType) {
		ModelResult<ArchiveRecordEntity> modelResult = new ModelResult<ArchiveRecordEntity>();
		try {
			ArchiveRecordEntity entity = archiveRecordDao.queryArchiveRecord(loanapplyNo, bankType, formType);
			modelResult.setModel(entity);
		} catch (Exception e) {
			logger.error("修改归档失败  loanapplyNo:[{}],bankType:[{}],formType:[{}],errorMsg:[{}]", loanapplyNo, bankType,
					formType, e);
			modelResult.withError("ArchiveRecordServiceImpl.queryArchiveRecord", "查询归档失败:" + e.getMessage());
			return modelResult;
		}
		return modelResult;
	}

	@Override
	public int updateArchiveRecordContentJson(String id, String json) {
		return archiveRecordDao.updateArchiveRecordContentJson(id, json);
	}

	@Override
	public CreditArchiveRecordEntity getById(String id) {
		return archiveRecordDao.getById(CreditArchiveRecordEntity.class, id);
	}

	@Override
	public PageResult<Object[]> queryCreditArchive(ArchivequeryForm achivequeryForm) {
		StringBuffer sql = new StringBuffer(" SELECT a.id , b.bill_code, a.credit_time, opr.province_name, dd.item_name as d1, "
				+ " CONCAT(b.ltd_code,'-',b.ltd_name) AS ltd_name, b.loan_type, a.customer_type, " +
				"a.customer_name, CONCAT( LEFT (a.id_card, 3), '****', RIGHT (a.id_card, 3)), dd4.item_name as d4, "
				+ "a.status,a.wf_status,operator_name  FROM "
				+ " o2o_credit_archive_record a "
				+ " LEFT JOIN o2o_loanapply b on a.bill_code = b.bill_code "
				+ " LEFT JOIN o2o_platform_regional opr on b.ltd = opr.platform_id "
				+ " LEFT JOIN pub_dditem dd on dd.dd_no='10340' and b.bank_type=dd.item_code "
				+ " LEFT JOIN pub_dditem dd4 on dd4.dd_no='10340' and b.bank_loan_name=dd4.item_code "
				+ " where /**DATA_PERMISSION(b.LTD)**/ 1=1 ");
		SqlPageQuery<Object[]> pageQuery = new SqlPageQuery<Object[]>(Object[].class, achivequeryForm.getPageSize(),
				achivequeryForm.getO2oIndex());
		if (StringUtil.hasText(achivequeryForm.getBillCode())) {
			sql.append(" AND b.bill_code like ? ");
			pageQuery.addLikeParam(achivequeryForm.getBillCode());
		}

		if (StringUtil.isNotBlank(achivequeryForm.getUserFullName())) {
			sql.append(" and a.customer_name like ? ");
			pageQuery.addLikeParam(achivequeryForm.getUserFullName());
		}

		if (StringUtil.isNotBlank(achivequeryForm.getCreditStartDate())) {
			sql.append(" and credit_time >= ?  ");
			pageQuery.addParam(achivequeryForm.getCreditStartDate());
		}

		if (StringUtil.isNotBlank(achivequeryForm.getCreditEndDate())) {
			sql.append(" and  credit_time <= ? ");
			pageQuery.addParam(achivequeryForm.getCreditEndDate());
		}
		if (StringUtil.isNotBlank(achivequeryForm.getStatus())) {
			sql.append(" and  status = ? ");
			pageQuery.addParam(achivequeryForm.getStatus());
		}
		if (StringUtil.isNotBlank(achivequeryForm.getWfStatus())) {
			sql.append(" and  wf_status = ? ");
			pageQuery.addParam(achivequeryForm.getWfStatus());
		}
		if (StringUtil.isNotBlank(achivequeryForm.getCreditBankLoan())) {
			sql.append(" and  bank_type = ? ");
			pageQuery.addParam(achivequeryForm.getCreditBankLoan());
		}
		if (StringUtil.isNotBlank(achivequeryForm.getHostProvince())) {
			sql.append(" and  opr.province_code = ? ");
			pageQuery.addParam(achivequeryForm.getHostProvince());
		}
		pageQuery.setQuerySql(sql.toString());
		return archiveRecordDao.findDataWithPage(pageQuery);
	}

	@Override
	public PageResult<Object[]> queryCreditArchiveDownloadData(ArchivequeryForm achivequeryForm) {
		StringBuffer sql = new StringBuffer(" SELECT b.bill_code, a.credit_time, opr.province_name, dd.item_name as d1, "
				+ " CONCAT(b.ltd_code,'-',b.ltd_name) AS ltd_name, dd2.item_name as d2, dd3.item_name as d3, "
				+ " a.customer_name, CONCAT( LEFT (a.id_card, 3), '****', RIGHT (a.id_card, 3)), dd4.item_name as d4, "
				+ " dd5.item_name as d5, dd6.item_name as d6, operator_name FROM "
				+ " o2o_credit_archive_record a "
				+ " LEFT JOIN o2o_loanapply b on a.bill_code = b.bill_code "
				+ " LEFT JOIN o2o_platform_regional opr on b.ltd = opr.platform_id "
				+ " LEFT JOIN pub_dditem dd on dd.dd_no='10340' and b.bank_type=dd.item_code "
				+ " LEFT JOIN pub_dditem dd2 on dd2.dd_no='11321' and b.loan_type=dd2.item_code "
				+ " LEFT JOIN pub_dditem_o2o dd3 on dd3.dd_no='13' and a.customer_type=dd3.item_code "
				+ " LEFT JOIN pub_dditem dd4 on dd4.dd_no='10340' and b.bank_loan_name=dd4.item_code "
				+ " LEFT JOIN pub_dditem_o2o dd5 on dd5.dd_no='2000001' and a.status=dd5.item_code "
				+ " LEFT JOIN pub_dditem_o2o dd6 on dd6.dd_no='2000002' and a.wf_status=dd6.item_code "
				+ " where /**DATA_PERMISSION(b.LTD)**/ 1=1 ");
		SqlPageQuery<Object[]> pageQuery = new SqlPageQuery<Object[]>(Object[].class, achivequeryForm.getPageSize(),
				achivequeryForm.getO2oIndex());
		if (StringUtil.hasText(achivequeryForm.getBillCode())) {
			sql.append(" AND b.bill_code like ? ");
			pageQuery.addLikeParam(achivequeryForm.getBillCode());
		}

		if (StringUtil.isNotBlank(achivequeryForm.getUserFullName())) {
			sql.append(" and a.customer_name like ? ");
			pageQuery.addLikeParam(achivequeryForm.getUserFullName());
		}

		if (StringUtil.isNotBlank(achivequeryForm.getCreditStartDate())) {
			sql.append(" and credit_time >= ?  ");
			pageQuery.addParam(achivequeryForm.getCreditStartDate());
		}

		if (StringUtil.isNotBlank(achivequeryForm.getCreditEndDate())) {
			sql.append(" and  credit_time <= ? ");
			pageQuery.addParam(achivequeryForm.getCreditEndDate());
		}
		if (StringUtil.isNotBlank(achivequeryForm.getStatus())) {
			sql.append(" and  status = ? ");
			pageQuery.addParam(achivequeryForm.getStatus());
		}
		if (StringUtil.isNotBlank(achivequeryForm.getWfStatus())) {
			sql.append(" and  wf_status = ? ");
			pageQuery.addParam(achivequeryForm.getWfStatus());
		}
		if (StringUtil.isNotBlank(achivequeryForm.getCreditBankLoan())) {
			sql.append(" and  bank_type = ? ");
			pageQuery.addParam(achivequeryForm.getCreditBankLoan());
		}
		if (StringUtil.isNotBlank(achivequeryForm.getHostProvince())) {
			sql.append(" and  opr.province_code = ? ");
			pageQuery.addParam(achivequeryForm.getHostProvince());
		}
		pageQuery.setQuerySql(sql.toString());
		return archiveRecordDao.findDataWithPage(pageQuery);
	}

	@Override
	public PageResult<Object[]> queryNewCreditArchive(ArchivequeryForm achivequeryForm) {
		StringBuffer sql = new StringBuffer(" SELECT a.id , a.bill_code, a.credit_time, opr.province_name, dd.item_name as d1, "
				+ " CONCAT(z.ltd_code,'-',z.ltd_name) AS ltd_name,a.customer_type, " +
				"	a.customer_name, CONCAT( LEFT (a.id_card, 3), '****', RIGHT (a.id_card, 3)), "
				+ " a.status,a.wf_status,l.operator_name  FROM o2o_credit_archive_record a  "
				+ " LEFT JOIN o2o_zx z on a.loanapply_no = z.id "
				+ " LEFT JOIN o2o_platform_regional opr on z.ltd = opr.platform_id  "
				+ " LEFT JOIN pub_dditem dd on dd.dd_no='10340' and z.zx_bank=dd.item_code "
				+ " LEFT JOIN o2o_loanapply l on l.loanapply_no = a.loanapply_no  where  ");
				///+ " where /**DATA_PERMISSION(z.ltd)**/ 1=1 ");
		
		sql.append(" 1=1 and (l.creat_ro="+UserHolder.getUser().getNo());
		if (!StringUtils.isEmpty(achivequeryForm.getXdjlNo())) {
			sql.append(" or l.operator_no in ("+achivequeryForm.getXdjlNo()+"))");
		}else {
			sql.append(" or /**DATA_PERMISSION(l.ltd)**/ 1=1 ) ");
		}
	
		
		SqlPageQuery<Object[]> pageQuery = new SqlPageQuery<Object[]>(Object[].class, achivequeryForm.getPageSize(),
				achivequeryForm.getO2oIndex());
		if (StringUtil.hasText(achivequeryForm.getBillCode())) {
			sql.append(" AND a.bill_code like ? ");
			pageQuery.addLikeParam(achivequeryForm.getBillCode());
		}

		if (StringUtil.isNotBlank(achivequeryForm.getUserFullName())) {
			sql.append(" and a.customer_name like ? ");
			pageQuery.addLikeParam(achivequeryForm.getUserFullName());
		}

		if (StringUtil.isNotBlank(achivequeryForm.getCreditStartDate())) {
			sql.append(" and a.credit_time >= ?  ");
			pageQuery.addParam(achivequeryForm.getCreditStartDate());
		}

		if (StringUtil.isNotBlank(achivequeryForm.getCreditEndDate())) {
			sql.append(" and  a.credit_time <= ? ");
			pageQuery.addParam(achivequeryForm.getCreditEndDate());
		}
		if (StringUtil.isNotBlank(achivequeryForm.getStatus())) {
			sql.append(" and  a.status = ? ");
			pageQuery.addParam(achivequeryForm.getStatus());
		}
		if (StringUtil.isNotBlank(achivequeryForm.getWfStatus())) {
			sql.append(" and  a.wf_status = ? ");
			pageQuery.addParam(achivequeryForm.getWfStatus());
		}
		if (StringUtil.isNotBlank(achivequeryForm.getCreditBankLoan())) {
			sql.append(" and  z.zx_bank = ? ");
			pageQuery.addParam(achivequeryForm.getCreditBankLoan());
		}
		if (StringUtil.isNotBlank(achivequeryForm.getHostProvince())) {
			sql.append(" and  opr.province_code = ? ");
			pageQuery.addParam(achivequeryForm.getHostProvince());
		}
		pageQuery.setQuerySql(sql.toString());
		return archiveRecordDao.findDataWithPage(pageQuery);
	}

	@Override
	public PageResult<Object[]> queryNewCreditArchiveDownloadData(ArchivequeryForm achivequeryForm) {
		StringBuffer sql = new StringBuffer(" SELECT a.bill_code,a.credit_time, opr.province_name, dd.item_name as d1, "
				+ " CONCAT(z.ltd_code,'-',z.ltd_name) AS ltd_name, dd3.item_name as d3, "
				+ " a.customer_name, CONCAT( LEFT (a.id_card, 3), '****', RIGHT (a.id_card, 3)), "
				+ " dd5.item_name as d5, dd6.item_name as d6, z.operator_name FROM "
				+ " o2o_credit_archive_record a  "
				+ " LEFT JOIN o2o_zx z on a.loanapply_no = z.id "
				+ " LEFT JOIN o2o_platform_regional opr on z.ltd = opr.platform_id  "
				+ " LEFT JOIN pub_dditem dd on dd.dd_no='10340' and z.zx_bank =dd.item_code  "
				+ " LEFT JOIN pub_dditem_o2o dd3 on dd3.dd_no='13' and a.customer_type=dd3.item_code  "
				+ " LEFT JOIN pub_dditem_o2o dd5 on dd5.dd_no='2000001' and a.status=dd5.item_code "
				+ " LEFT JOIN pub_dditem_o2o dd6 on dd6.dd_no='2000002' and a.wf_status=dd6.item_code  "
				+ " LEFT JOIN o2o_loanapply l on l.loanapply_no = a.loanapply_no  where  ");
				///+ " where /**DATA_PERMISSION(z.ltd)**/ 1=1 ");

				sql.append(" 1=1 and (l.creat_ro="+UserHolder.getUser().getNo());
				if (!StringUtils.isEmpty(achivequeryForm.getXdjlNo())) {
					sql.append(" or l.operator_no in ("+achivequeryForm.getXdjlNo()+"))");
				}else {
					sql.append(" or /**DATA_PERMISSION(l.ltd)**/ 1=1 ) ");
				}
		
		
		SqlPageQuery<Object[]> pageQuery = new SqlPageQuery<Object[]>(Object[].class, achivequeryForm.getPageSize(),
				achivequeryForm.getO2oIndex());
		if (StringUtil.hasText(achivequeryForm.getBillCode())) {
			sql.append(" AND a.bill_code like ? ");
			pageQuery.addLikeParam(achivequeryForm.getBillCode());
		}

		if (StringUtil.isNotBlank(achivequeryForm.getUserFullName())) {
			sql.append(" and a.customer_name like ? ");
			pageQuery.addLikeParam(achivequeryForm.getUserFullName());
		}

		if (StringUtil.isNotBlank(achivequeryForm.getCreditStartDate())) {
			sql.append(" and credit_time >= ?  ");
			pageQuery.addParam(achivequeryForm.getCreditStartDate());
		}

		if (StringUtil.isNotBlank(achivequeryForm.getCreditEndDate())) {
			sql.append(" and  credit_time <= ? ");
			pageQuery.addParam(achivequeryForm.getCreditEndDate());
		}
		if (StringUtil.isNotBlank(achivequeryForm.getStatus())) {
			sql.append(" and  status = ? ");
			pageQuery.addParam(achivequeryForm.getStatus());
		}
		if (StringUtil.isNotBlank(achivequeryForm.getWfStatus())) {
			sql.append(" and  wf_status = ? ");
			pageQuery.addParam(achivequeryForm.getWfStatus());
		}
		if (StringUtil.isNotBlank(achivequeryForm.getCreditBankLoan())) {
			sql.append(" and  bank_type = ? ");
			pageQuery.addParam(achivequeryForm.getCreditBankLoan());
		}
		if (StringUtil.isNotBlank(achivequeryForm.getHostProvince())) {
			sql.append(" and  opr.province_code = ? ");
			pageQuery.addParam(achivequeryForm.getHostProvince());
		}
		pageQuery.setQuerySql(sql.toString());
		return archiveRecordDao.findDataWithPage(pageQuery);
	}
}
